const app = getApp();
var utils = require("../../utils/utils.js");
var server = require("../../utils/server.js");
var config = require("../../config.js");
var apis = require("../../utils/api.js");

Page({
  data: {
    authStatus: app.globalData.userInfo.authStatus,
    sortingPortNumber: '',
    lastIndex: '',
    batchNumber: '',
    dataList: [{
      materialNumber: '',
      materialBatchNumber: '',
      quantity: ''
    }],
    options: [],
    selectedOption: '',
    showSwitch: false,
    hideSwitch: true,
    isEdit: false,
    bgColor: '#ffffff', // 初始颜色为白色
    opacity: 1,
    isPressed1: false,
    isPressed2: false
  },

  onTouchStart: function (e) {
    const index = e.currentTarget.dataset.index; // 获取当前项目的索引
    const dataList = this.data.dataList.slice(); // 复制当前数组
    dataList[index].bgColor = '#f1f1f1'; // 设置为灰色
    this.setData({
      dataList: dataList // 更新数据
    });
  },

  onTouchEnd: function (e) {
    const index = e.currentTarget.dataset.index; // 获取当前项目的索引
    const dataList = this.data.dataList.slice(); // 复制当前数组
    dataList[index].bgColor = '#ffffff'; // 恢复为白色
    this.setData({
      dataList: dataList // 更新数据
    });
  },

  handleTouchStart1() {
    this.setData({
      isPressed1: true
    });
  },

  handleTouchEnd1() {
    this.setData({
      isPressed1: false
    });
  },

  handleTouchStart2() {
    this.setData({
      isPressed2: true
    });
  },

  handleTouchEnd2() {
    this.setData({
      isPressed2: false
    });
  },

  onShow(options) {
    this.listWithPendingCount()
  },

  bindPickerChange: function (e) {
    let _this = this
    let selectedOption = _this.data.options[e.detail.value]
    let sortingPortNumber = selectedOption.substring(0, selectedOption.indexOf('号'));
    console.log('当前选择的分拣口信息', sortingPortNumber, selectedOption)
    _this.setData({
      isEdit: true,
      selectedOption,
      sortingPortNumber
    })
  },

  listWithPendingCount() {
    let _this = this;
    var prams = {}
    let api = apis.listWithPendingCount;
    server.getRequest(config.xburl, api, prams,
      function (res) {
        let data = res.data
        const options = data.map(item => `${item.sortingPortNumber}号口 待分拣数量: ${item.pendingCount}`);
        const index = data.findIndex(item => item.sortingPortNumber == _this.data.sortingPortNumber);
        _this.setData({
          options: options,
          selectedOption: options[index]
        })
      },
      function (err) {
        utils.showToast(err)
      })
  },

  /**
   * @description: 获取编码
   * @param {type}
   * @return:
   */
  bindBmInput: function (e) {
    let _this = this
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    if (value.length > 25) {
      utils.showToast('编码长度有误，请检查')
      return
    }
    let newItems = [..._this.data.dataList];
    newItems[index]['materialNumber'] = value;
    _this.setData({
      isEdit: true,
      dataList: newItems
    })
  },

  /**
   * @description: 获取分拣批次号
   * @param {type}
   * @return:
   */
  bindBatchNumber: function (e) {
    let _this = this
    let value = e.detail.value
    _this.setData({
      isEdit: true,
      batchNumber: value
    })
  },

  bindWlpcInput: function (e) {
    let _this = this
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    if (value.length > 25) {
      utils.showToast('物料批次号长度有误，请检查')
      return
    }
    let newItems = [..._this.data.dataList];
    newItems[index]['materialBatchNumber'] = value;
    _this.setData({
      isEdit: true,
      dataList: newItems
    })
  },



  /**
   * @description: 获取数量
   * @param {type}
   * @return:
   */
  bindSlInput: function (e) {
    let _this = this
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    let dataList = _this.data.dataList;
    const reg = /^(?!0\d)\d+(\.\d+)?$/;
    // 输入数量最大不超1000
    if (!reg.test(value)) {
      utils.showToast('请您输入非零整数')
      dataList[index]['quantity'] = '';
    } else if (parseInt(value) > 1000) {
      utils.showToast('请您输入小于1000的整数')
    } else {
      dataList[index]['quantity'] = parseInt(value);
    }
    _this.setData({
      isEdit: true,
      dataList: dataList
    })
  },

  bindDelete(e) {
    this.onTouchEnd(e)
    wx.showModal({
      title: '温馨提示',
      content: '是否删除',
      complete: (res) => {
        if (res.cancel) {
          return
        }
        if (res.confirm) {
          let _this = this
          const index = e.currentTarget.dataset.index;
          let dataList = _this.data.dataList
          if (dataList.length == 1) {
            utils.showToast('已经是最后一项了')
            return
          }
          dataList.splice(index, 1)
          setTimeout(function () {
            utils.showToast('已删除')
          }, 100);
          _this.setData({
            dataList: dataList,
            lastIndex: ''
          })
        }
      }
    })
  },


  // 添加新项函数
  bindAddRow() {
    let _this = this
    let array = _this.data.dataList
    let newItem = []
    let dataList = []
    if (array.length === 0) {
      dataList = [{
        materialNumber: '',
        quantity: '',
        materialBatchNumber: ''
      }]

    } else {
      // 获取第一个元素的键
      const keys = Object.keys(array[0]);
      // 创建新对象，所有值为空字符串
      newItem = keys.reduce((obj, key) => {
        obj[key] = '';
        return obj;
      }, {});
      dataList = [...array, newItem]
    }
    _this.setData({
      isEdit: true,
      dataList
    })
  },

  // 创建物料信息

  bindSubmit() {
    wx.showModal({
      title: '温馨提示',
      content: '是否保存并提交',
      complete: (res) => {
        if (res.cancel) {
          return
        }
        if (res.confirm) {
          let _this = this
          let materialInfoList = [];
          let originalArray = _this.data.dataList;
          let batchNumber = _this.data.batchNumber
          // 必须配置物料信息
          if (originalArray.length === 0) {
            return utils.showToast('请先录入物料信息')
          }
          // 字段分拣批次号格式必须合法
          if (batchNumber) {
            const regex = /^(\d{2}|\d{4})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])$/;
            if (!regex.test(batchNumber)) {
              return utils.showToast(`分拣批次号格式验证失败：${batchNumber} 不符合 (YY|YYYY)MMDD 格式。`)
            }
          }
          for (let i = 0; i < originalArray.length; i++) {
            let item = originalArray[i];
            let newItem = {};
            newItem.id = ""
            // 校验：物料编码和数量必填
            if (!item['materialNumber'] || !item['quantity']) {
              return utils.showToast('请您先将信息填写完整')
            }
            // 校验：数值合法性
            if (!Number.isInteger(Number(item['quantity']))) {
              return utils.showToast('请您输入正确的数量')
            }
            newItem.materialNumber = item['materialNumber'];
            newItem.materialBatchNumber = item['materialBatchNumber'] != undefined ? item['materialBatchNumber'] : '';
            newItem.quantity = item['quantity'];
            newItem.enterpriseId = app.globalData.userInfo.entId;
            newItem.deliveryNoteId = '';
            newItem.sortingStatus = 2;
            materialInfoList.push(newItem);
          }

          // 隐藏批次号时，上传字段全部传空
          let newDataList = []
          if (_this.data.showSwitch && _this.data.hideSwitch) {
            newDataList = materialInfoList.map(item => {
              // 如果对象中有isFLag属性，则将其值置为空
              if (item.hasOwnProperty('materialBatchNumber')) {
                return {
                  ...item,
                  materialBatchNumber: ''
                };
              }
              return item;
            });
          }

          let params = {
            "deliveryNote": {
              "entCustomerId": app.globalData.userInfo.entId,
              "id": '',
              "batchNumber": _this.data.batchNumber,
              "noteDescription": '手工录入',
              "photoAddress": '',
              "sortingPortNumber": _this.data.sortingPortNumber
            },
            "materialInfoList": newDataList.length > 0 ? newDataList : materialInfoList
          }
          let url = apis.createCombind
          server.postRequest(config.xburl, url, params,
            function (res) {
              // 保存成功清空
              _this.setData({
                dataList: [{
                  materialNumber: '',
                  materialBatchNumber: '',
                  quantity: ''
                }],
                lastIndex: '',
                batchNumber: '',
              })
              let params = {
                type: 'ocr',
                tip: '保存提交成功！'
              }
              wx.navigateTo({
                url: '/pages/Result/Result?value=' + JSON.stringify(params),
              })
            },
            function (err) {
              utils.showToast(err)
            })

        }
      }
    })
  },

  toSumView() {
    let _this = this
    let dataList = _this.data.dataList
    let len = dataList.length
    if (dataList.length === 0) {
      utils.showToast('请先录入物料信息')
      return
    }
    let total = 0;
    let isCheck = false
    dataList.forEach(item => {
      // 值合法性校验
      if (!Number.isInteger(Number(item['quantity']))) {
        isCheck = false
      } else {
        // 将数量转换为整数并累加
        total += parseInt(item['quantity']) || 0;
        isCheck = true
      }
    });
    if (!isCheck) {
      utils.showToast('数量输入有误')
      return
    } else {
      let content = `${len}个物料，共计${total}件`
      wx.showModal({
        title: '温馨提示',
        content: content,
        showCancel: false,
        complete: (res) => {
          if (res.confirm) {

          }
        }
      })
    }
  },

  switchChange() {
    let _this = this
    let {
      dataList
    } = _this.data
    if (dataList.length === 0) {
      utils.showToast('请先录入物料信息')
      return
    }
    _this.setData({
      hideSwitch: !_this.data.hideSwitch
    })
  },

  listWithPendingCount() {
    let _this = this;
    var prams = {}
    let api = apis.listWithPendingCount;
    server.getRequest(config.xburl, api, prams,
      function (res) {
        let data = res.data
        console.log('查询分拣口', data)
        const options = data.map(item => `${item.sortingPortNumber}号口 待分拣数量：${item.pendingCount}`);
        const minIndex = data.reduce((minIndex, currentObj, currentIndex) => {
          if (currentObj.pendingCount < data[minIndex].pendingCount) {
            return currentIndex;
          }
          return minIndex;
        }, 0);
        console.log('options[minIndex]', minIndex, options[minIndex])
        _this.setData({
          options: options,
          selectedOption: options[minIndex],
          sortingPortNumber: data[minIndex]['sortingPortNumber']
        })
      },
      function (err) {
        utils.showToast(err)
      })
  },
});